<?php

namespace App\Admin\Controllers\Admin;

use App\Models\User\WxUser;
use App\Models\WxChat;
use App\Wen\Utils\StrUtils;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Form;
use Dcat\Admin\Traits\HasFormResponse;
use Illuminate\Http\Request;
use Dcat\Admin\Admin;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class AdminToolsController extends AdminController
{
    use HasFormResponse;

    public function imgDomainReplaceHandler(Request $request){
        $old_str = $request->old_str;
        $new_str = $request->new_str;

        if(_empty_($old_str)){
            return $this->response()->error('请输入旧字符串');
        }
        if(_empty_($new_str)){
            $new_str = '';
        }
        $admin_user = Admin::user();
        if(!($admin_user && $admin_user->isAdministrator())){
            return $this->response()->error('你不是超级管理员');
        }

        DB::beginTransaction();
        try {
            // todo:
            $tables = DB::select('SHOW TABLES');
            $tableNames = array_map('current', $tables);
            if($tableNames){
                foreach ($tableNames as $table_name){
                    if(StrUtils::startsWith($table_name, 'admin_')){
                        continue;
                    }
                    if(!StrUtils::startsWith($table_name, 'wx_') && !StrUtils::startsWith($table_name, 'mini_')){
                        continue;
                    }
                    $table_info_columns = DB::select( DB::raw('SHOW COLUMNS FROM '.$table_name));
                    foreach($table_info_columns as $column){
                        if(in_array($column->Field, ['id', 'deleted_at', 'created_at', 'updated_at']) || StrUtils::endsWith($column->Field, '_id')){
                            continue;
                        }
                        if(strpos($column->Type, 'int') !== false){
                            continue;
                        }
                        if(in_array($column->Field, ['desc', 'right', 'condition', 'key'])){
                            continue;
                        }
                        DB::select("UPDATE ".$table_name." SET ".$column->Field." = REPLACE(".$column->Field.", '".$old_str."', '".$new_str."') WHERE ".$column->Field." LIKE '%".$old_str."%'");
                    }
                }
            }

            Cache::tags('st')->flush();

            DB::commit();
            return $this->response()->success('替换成功！')->refresh();
        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return $this->response()->error($e->getMessage());
        }
    }

    public function imgDomainReplaceForm(Content $content)
    {
        return Form::make('',function (Form $form) {

            $form->text('old_str', '旧字符串')->required();
            $form->text('new_str', '新字符串');

            $form->disableResetButton();
            $form->action('admin/tools/img_domain_replace');
        });
    }

    public function chatRecordChangeHandler(Request $request){
        $user_1 = (int)($request->user_1);
        $user_2 = (int)($request->user_2);

        if(_empty_($user_1) || $user_1 <= 0){
            return $this->response()->error('账号A参数错误');
        }
        if(_empty_($user_2) || $user_2 <= 0){
            return $this->response()->error('账号B参数错误');
        }

        $user_model_1 = WxUser::find($user_1);
        $user_model_2 = WxUser::find($user_2);

        if(!($user_model_1 && $user_model_2)){
            return $this->response()->error('账号实际不存在');
        }

        $admin_user = Admin::user();
        if(!($admin_user && $admin_user->isAdministrator())){
            return $this->response()->error('你不是超级管理员');
        }

        DB::beginTransaction();
        try {
            WxChat::where('user_id', $user_1)->update(['user_id' => $user_2]);
            WxChat::where('object_id', $user_1)->update(['object_id' => $user_2]);
            DB::commit();
            return $this->response()->success('迁移成功！')->refresh();
        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return $this->response()->error($e->getMessage());
        }
    }

    public function chatRecordChangeForm(Content $content)
    {
        return Form::make('',function (Form $form) {

            $form->text('user_1', '账号A')->help('A账号的所有聊天记录转移到B账号')->required();
            $form->text('user_2', '账号B')->required();

            $form->disableResetButton();
            $form->action('admin/tools/chat_record_change');
        });
    }

    public function tools(Content $content)
    {
        Form::dialog('数据库字符串替换')
            ->click('#img-domain-replace') // 绑定点击按钮
            ->url('admin/tools/img_domain_replace') // 表单页面链接，此参数会被按钮中的 “data-url” 属性替换。。
            ->height('650px;overflow: hidden;') // 指定弹窗高度，可填写百分比，默认 690px
            ->success('Dcat.reload()'); // 新增成功后刷新页面

        Form::dialog('聊天记录迁移')
            ->click('#chat-record-change') // 绑定点击按钮
            ->url('admin/tools/chat_record_change') // 表单页面链接，此参数会被按钮中的 “data-url” 属性替换。。
            ->height('650px;overflow: hidden;') // 指定弹窗高度，可填写百分比，默认 690px
            ->success('Dcat.reload()'); // 新增成功后刷新页面

        return $content
            ->title('管理员工具箱')
            ->description('注意：操作之前先<b style="color: red;">备份数据库</b>，世上没有后悔药，这里面都是属于高危操作，没事少碰，如果没有备份数据库就进行操作，中间出现了的问题，群主不会解答')
            ->body(admin_view('admin.pages.admin-tools', [
                'paycode_0' => true,
            ]));
    }
}
